﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TPOJ.Core;
using TPOJ.Model;

namespace TPOJ.BLL
{
    public static class Utils
    {

        internal static int GetContestProblemLabel(int contestId, int problemId)
        {
            ContestBO contestBO = new ContestBO();
            var pids = contestBO.GetContest(contestId).Problems.OrderBy(p => p.UniqueID).Select(p => p.UniqueID).ToArray();
            return Array.FindIndex(pids, id => id == problemId);
        }

        public static void UpdateStanding(int contestId, int accountId, int cellId, DateTime submitTime, ResultType result, int submitsIncrement)
        {
            ContestBO contestBO = new ContestBO();
            var contest = contestBO.GetContest(contestId);

            var standing = contestBO.FindContestStanding(contestId, accountId);
            if (standing == null)
            {
                standing = contestBO.AddContestStanding(contestId, accountId);
            }

            StandingCell cell = contestBO.FindContestStandingCell(standing.UniqueId, cellId);
            if (cell == null)
            {
                cell = contestBO.AddContestStandingCell(standing.UniqueId, cellId);
            }

            int submits = (cell.Submits ?? 0) + submitsIncrement;
            int time = cell.Time ?? 0;
            int waSubmits = cell.WA_Submits ?? 0;
            if (result == ResultType.Accepted) //accepted
            {
                TimeSpan difference = submitTime - contest.StartTime;
                time = difference.Minutes;
            }
            else
            {
                if (result == ResultType.Pending || result == ResultType.Compiling || result == ResultType.Judging || result == ResultType.Running) //pending
                {
                    if (cell.Time == -1 || cell.Time == -2 || cell.Time ==0)
                    {
                        time = -1;
                    }
                }
                else //rejected
                {
                    if (cell.Time == -1 || cell.Time == -2 || cell.Time ==0)
                    {
                        waSubmits++;
                        time = -2;
                    }
                }
            }
            contestBO.EditContestStandingCell(cell.Id, cell.StandingId, time, waSubmits, submits);
            contestBO.RefreshStanding(standing.UniqueId);
        }

    }
}
